package com.itheima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUtils {
    //硬编码,复用性差,可以写到配置文件中,通过注解@Value(${名称})
    /*String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    String accessKeyId = "LTAI5t8JdCqi7hmkQZXgbNmo";
    String accessKeySecret = "0czQK68noZb8Coz8Fp7Iq80oc6nSmy";
    String bucketName = "web-myproject01";*/

    /* //使用properties配置,声明属性,通过@Value注入
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;*/

    //yml文件配置,把参数封装进类,通过Bean自动注入
    @Autowired
    private ALiOSSProperties aLiOSSProperties;


    //上传文件到阿里云
    public String upload(MultipartFile file) throws IOException {
        //yml获取参数
        String endpoint = aLiOSSProperties.getEndpoint();
        String accessKeyId = aLiOSSProperties.getAccessKeyId();
        String accessKeySecret = aLiOSSProperties.getAccessKeySecret();
        String bucketName = aLiOSSProperties.getBucketName();

        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
        //获取文件输入流
        InputStream inputStream=file.getInputStream();
        //文件重命名
        String originalFilename = file.getOriginalFilename();
        /*int index = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(index);
        String newFileName= UUID.randomUUID().toString()+substring;*/
        //简写
        String newFileName= UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
        // 创建OSSClient实例,上传文件
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        ossClient.putObject(bucketName,newFileName,inputStream);
        //文件访问路径
        String url=endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+newFileName;
        //关闭oss
        ossClient.shutdown();
        return url;
    }
}
